<template>
  <div class="p-6">
    <h2 class="text-2xl font-bold mb-4">订单管理</h2>

    <!-- 表格 -->
    <el-table
      :data="orders"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      border
    >
      <el-table-column prop="orderlistId" label="订单ID" width="120" />
      <el-table-column prop="userId" label="用户ID" width="120" />
      <el-table-column prop="deskId" label="桌号" width="100" />
      <el-table-column prop="orderlistPrice" label="总价" width="120" />

      <!-- 状态选择 -->
      <el-table-column prop="orderlistStatus" label="订单状态" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.orderlistStatus"
            placeholder="请选择"
            size="small"
            @change="updateOrder(scope.row)"
          >
            <el-option label="未支付" value="未支付" />
            <el-option label="已支付" value="已支付" />
            <el-option label="制作中" value="制作中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 进度条 -->
      <el-table-column label="订单进度" width="200">
        <template #default="scope">
          <el-progress
            :percentage="getProgress(scope.row.orderlistStatus).percent"
            :status="getProgress(scope.row.orderlistStatus).status"
            :stroke-width="16"
          />
        </template>
      </el-table-column>

      <!-- 格式化为中国大陆时间 -->
      <el-table-column prop="orderlistTime" label="下单时间" width="200">
        <template #default="scope">
          {{ formatTime(scope.row.orderlistTime) }}
        </template>
      </el-table-column>

      <el-table-column prop="employeeId" label="员工ID" width="120" />
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex justify-end">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { get } from '../utils/axios'
import { ElMessage } from 'element-plus'

const orders = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const storeId = localStorage.getItem('storeId') || 1  // 默认门店ID

// 格式化时间为中国大陆时间
function formatTime(val) {
  if (!val) return ''
  const date = new Date(val)
  return date.toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 状态 → 进度 & 颜色映射
function getProgress(status) {
  switch (status) {
    case '未支付':
      return { percent: 0, status: 'exception' }   // 红色
    case '已支付':
      return { percent: 25, status: 'success' }   // 绿色
    case '制作中':
      return { percent: 60, status: 'warning' }   // 黄色
    case '已完成':
      return { percent: 100, status: 'success' }  // 绿色
    case '已取消':
      return { percent: 100, status: 'exception' } // 红色
    default:
      return { percent: 0, status: 'text' }
  }
}

// 加载订单（分页）
async function loadOrders(page = 1) {
  loading.value = true
  try {
    const res = await get('/orderlist/all', {
      storeId,
      page,
      size: pageSize.value,
    })
    orders.value = res.records || []
    total.value = res.total || 0
    currentPage.value = page
  } catch (e) {
    console.error('加载订单失败', e)
    ElMessage.error('加载订单失败')
  } finally {
    loading.value = false
  }
}

// 更新订单状态（局部更新，不刷新整页）
async function updateOrder(order) {
  try {
    const res = await get('/orderlist/updateStatus', {
      orderlistId: order.orderlistId,
      orderlistStatus: order.orderlistStatus,
    })
    if (res === 'success') {
      if (order.orderlistStatus === '已取消') {
        ElMessage.warning('订单已取消，库存已回补')
      } else {
        ElMessage.success('状态已更新')
      }
    } else {
      ElMessage.error('更新失败')
    }
  } catch (e) {
    console.error('更新订单失败', e)
    ElMessage.error('更新失败')
  }
}



// 分页切换
function handlePageChange(page) {
  loadOrders(page)
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
/* 让分页器靠右 */
.el-pagination {
  justify-content: flex-end;
}
</style>
